#!/bin/sh
# smokey01 - 01 September 2016

[ $DISPLAY ] || exit

export TEXTDOMAIN=xswapmonitors
export OUTPUT_CHARSET=UTF-8

[ -z $GTKDIALOG ] && GTKDIALOG=gtkdialog

XRANDR="$(LANG=C xrandr 2>/dev/null)"
MONITOR_LIST=$(echo "$XRANDR" | grep connected | grep -v disconnected | sed 's| .*||')
if [ $(echo "$MONITOR_LIST" | wc -l) -lt 2 ] ; then
	ERRMSG="$(gettext "At lest 2 monitors must be connected..")"
	exec /usr/lib/gtkdialog/box_ok "$(gettext 'Swap Monitors')" error "$ERRMSG"
fi

# This generates a combobox list of monitors 
for I in $MONITOR_LIST ; do
	MONITORS=`echo "$MONITORS<item>$I</item>"`
done

#----------------

while [ 1 ] ; do

	if [ -s /root/Startup/setmonitors ] ; then
		BUTTON_DELETE='<button space-expand="false" space-fill="false">
				<label>'$(gettext 'Delete config')'</label>
				<action>exit:DELETE</action>
			</button>'
	fi
	SWAP_MONITORS_DIALOG='
<window icon-name="gtk-preferences" title="'$(gettext 'Swap Monitors')'"> 
	<vbox>
		'"`/usr/lib/gtkdialog/xml_info fixed network.svg 32 "$(gettext 'Select left and right monitor')"`"'
		<hbox>
			<combobox tooltip-text="'$(gettext 'Select Left Monitor')'">
				<variable>MONITOR0</variable>
				'${MONITORS}'
			</combobox>
			<combobox tooltip-text="'$(gettext 'Select Right Monitor')'">
				<variable>MONITOR1</variable>
				'${MONITORS}'
			</combobox>
		</hbox>
		<hbox>
			<button space-expand="false" space-fill="false">
				<input file stock="gtk-network"></input>
				<label>'$(gettext 'Swap')'</label>
				<action>exit:SWAP</action>
			</button>
			<button space-expand="false" space-fill="false">
				<input file stock="gtk-quit"></input>
				<label>'$(gettext 'Quit')'</label>
			</button>
			'${BUTTON_DELETE}'
		</hbox>
	</vbox>
</window>
'
	export SWAP_MONITORS_DIALOG

	case $1 in -d|--dump) echo "$SWAP_MONITORS_DIALOG" ; exit ;; esac

	. /usr/lib/gtkdialog/xml_info gtk #build bg_pixmap for gtk-theme
	eval "$($GTKDIALOG --center --program=SWAP_MONITORS_DIALOG)"
	if [ "$EXIT" = "SWAP" ] ; then
		xrandr --output $MONITOR0 --auto --output $MONITOR1 --auto --right-of $MONITOR0
		echo "#!/bin/sh
xrandr --output $MONITOR0 --auto --output $MONITOR1 --auto --right-of $MONITOR0" > /root/Startup/setmonitors
		chmod 755 /root/Startup/setmonitors
	elif [ "$EXIT" = "DELETE" ] ; then
		rm -f /root/Startup/setmonitors
		/usr/lib/gtkdialog/box_yesno --yes-first "$(gettext 'Delete config')" "$(gettext 'Do you want to restart X')"
		[ $? -eq 0 ] && restartwm
		break
	else
		break
	fi

done

### END ###
